const exporess = require('express')
const mongo = require('./models/db')

const app = exporess()

// 翻页查询
/*
    GET: '/api/list?offset=0&pageSize=4'

    [request]

    offset: 偏移量
    pageSize: 每一页多少行

    [response]

    {
        success: true
        data: {
            fruits: [],
            pagination: {
                total
                offset
                pageSize
            }
        }
    }

*/
app.get('/api/list', async (req, res) => {
    let { offset, pageSize } = req.query
    offset = parseInt(offset)
    pageSize = parseInt(pageSize)
    // console.log(1, `offset: ${offset}, pageSize: ${pageSize}`)

    let result = {
        success: false,
        data: { 
            fruits: {},
            pagination: { offset, pageSize, total: 0 }
        },
        error: null
    }

    try {
        let fruits = await mongo.col('fruits')
            .find()// 返回游标
            .skip(offset) // 跳过 n 行
            .limit(pageSize)// 选择 n 行
            .toArray();
        // console.log(2, 'fruits', fruits)

        result.data.fruits = fruits
        result.success = true

        const total = await mongo.col('fruits').find().count()
        result.data.pagination.total = total
        // console.log(3, 'total', total)
    } catch (error) {
        result.error = error
    }
    // console.log(4, result)
    res.json(result)
})

app.listen(80, () => {
    console.log('server is runing port: 80')
})
